

<template>
  <div class="talkContent">
    <div class="talkShow">
      <div :class="item.person === 'mechanical'?'mechanicalTalk':'mineTalk'" v-for="(item,index) in talkList" :key="index">
        <span>{{item.say}}</span>
      </div>
    </div>
    <div class="talkInput">
      <form @submit.prevent="getQuestion" class="userSearch">
        <el-input
            placeholder="请输入内容"
            v-model="contentVal"
            size="small">
          <i slot="suffix" class="el-input__icon el-icon-position" style="cursor: pointer;" @click="getQuestion"></i>
        </el-input>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name:"TestT2",
  data() {
    return {
      talkList: [
        { id:"1", person: 'mechanical', say: '你好，有什么可以帮到你呢？' },
      ],
      isMine: 1,
      contentVal: '',
    };
  },
  updated() {
    this.scrollToBottom();
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(()=> {
        let box = this.$el.querySelector(".talkShow");
        box.scrollTop = box.scrollHeight;
      })
    },
    getQuestion() {
      if (this.contentVal === '') {
        this.$message.error('请输入内容');
        return;
      }
      // admin提问数据push()
      this.talkList.push({ id: Date.now(), person:'admin', say: this.contentVal });
      // 清空输入栏数据
      this.contentVal = '';
      this.getAnswer();
    },
    async getAnswer() {
      // 调用API获取回答， 模拟后端返回的数据流式输出
      const data ='文字逐个展示，文字逐个展示，文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示';
      // mechanical 模拟回答
      this.talkList.push({ id: Date.now(), person:'mechanical', say: '...' });
      // 流式输出文字逐个展示
      let text = "";
      const length = this.talkList.length;
      for (let i = 0; i < data.length; i++) {
        text += data.charAt(i);
        await new Promise((resolve) => {
          setTimeout(resolve, 50)
        });
        this.talkList[length - 1].say= text;
      }
    }
  },
};
</script>

<style scoped>
.talkContent {
  width: 410px;
  margin: 50px auto 0;
  background-color: rgb(245, 246, 247);
  border-radius: 5px;
  font-size: 14px;
}

.talkShow {
  height: 400px;
  margin: 10px auto 0;
 /* overflow: scroll;*/
  overflow: hidden
}

.talkInput {
  margin: 10px auto 0;
  display: flex;
}

.mechanicalTalk {
  margin: 10px;
}

.mechanicalTalk span {
  display: inline-block;
  background: white;
  padding: 5px 10px;
  border: 1px solid rgb(214, 216, 219);
  border-radius: 0 10px 10px 10px;
  word-break: break-all;
  text-align: left;
}

.mineTalk {
  margin: 10px;
  text-align: right;
}

.mineTalk span {
  display: inline-block;
  border-radius: 10px 0px 10px 10px;
  background: #409eff;
  color: #fff;
  padding: 5px 10px;
  word-break: break-all;
  text-align: left;
}

</style>



